package com.gl.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Map;

/**
 * <p>Description:资源扫描</p>
 * 扫描系统所有Controller的请求地址，然后结合权限框架做基于URL的权限验证
 *
 * @author gaol
 * @version 1.0
 * @date 2017/5/16
 */
@Component
public class ScanResource {

    private static Logger logger = LoggerFactory.getLogger(ScanResource.class);

    @Autowired
    private RequestMappingHandlerMapping handlerMapping;


    public void createResource() {
        Map<RequestMappingInfo, HandlerMethod> map = handlerMapping.getHandlerMethods();
        for (RequestMappingInfo key : map.keySet()) {
            String resource = formatKey(key.getPatternsCondition().toString());
            String method = formatKey(key.getMethodsCondition().toString());
            if (StringUtils.isNotEmpty(resource) && StringUtils.isNotEmpty(method) && StringUtils.isNotEmpty(key.getName())) {
                logger.info("{},{},{}", resource, method, key.getName());
            }
        }
        // do something
    }


    private String formatKey(String resources) {
        if (StringUtils.isNotEmpty(resources)) {
            return resources.substring(1, resources.length() - 1);
        }
        return null;
    }
}
